# -*- coding: utf-8 -*-
import datetime
from django.db.models import permalink, signals
from google.appengine.ext import db
from google.appengine.ext.db import Model as DBModel
from django.contrib.auth.models import User
from google.appengine.api import memcache
import urllib, hashlib
from app1.views import del_html
from app1.models import Profile
from ragendja.dbutils import cleanup_relations

cur_app = "app2"

class Ads(db.Model):
    name = db.StringProperty(required=True)
    value = db.TextProperty()
    description = db.StringProperty()
    
    def __unicode__(self):
        return self.name    

class Category(db.Model):
    name = db.StringProperty(multiline=False)
    slug = db.StringProperty(multiline=False,default='')
    sort = db.IntegerProperty(default=0)
    entrycount = db.IntegerProperty(default=0)
    post_keys = db.ListProperty(db.Key)
    
    def __unicode__(self):
        return self.name
    
    @property
    def posts(self):
        men_key = "%s_category_posts_%d"%(cur_app,self.key().id())
        men_data = memcache.get(men_key)
        if men_data is None:
            men_data = db.get(self.post_keys[:20])
            memcache.add(men_key, men_data, 3600)
        return men_data
    
    @property
    def posts_index(self):
        men_key = "%s_category_posts_index_%d"%(cur_app,self.key().id())
        men_data = memcache.get(men_key)
        if men_data is None:
            men_data = db.get(self.post_keys[:10])
            memcache.add(men_key, men_data, 3800)
        return men_data    
    
    @permalink
    def get_absolute_url(self):
        if self.slug:
            title = self.slug.replace(' ','_')
        else:
            title = self.name.strip()
            title = title.replace(' ','_')
            title = title.replace(',','_')
            title = title.replace(u'，','_')
            title = title.replace("/","%2f")
            title = title.replace("%","%25")        
        return ('app2.views.category_article', (), {'keyid': self.key().id(),'name':title})    
    
signals.pre_delete.connect(cleanup_relations, sender=Category)

class BaseModel(db.Model):
    def __init__(self, parent=None, key_name=None, _app=None, **kwds):
        self.__isdirty = False
        DBModel.__init__(self, parent=None, key_name=None, _app=None, **kwds)

    def __setattr__(self,attrname,value):
        """
        DataStore api stores all prop values say "email" is stored in "_email" so
        we intercept the set attribute, see if it has changed, then check for an
        onchanged method for that property to call
        """
        if (attrname.find('_') != 0):
            if hasattr(self,'_' + attrname):
                curval = getattr(self,'_' + attrname)
                if curval != value:
                    self.__isdirty = True
                    if hasattr(self,attrname + '_onchange'):
                        getattr(self,attrname + '_onchange')(curval,value)

        DBModel.__setattr__(self,attrname,value)

class Entry(BaseModel):
    author = db.ReferenceProperty(User, collection_name='user_bbs_posts')
    author_profile = db.ReferenceProperty(Profile, collection_name='user_profile_bbs_posts')
    category = db.ReferenceProperty(Category, collection_name='cat_posts',required=True)
    title = db.StringProperty(multiline=False,default='')
    content = db.TextProperty(default='')
    commentclosed = db.BooleanProperty(default=False)
    commentcount = db.IntegerProperty(default=0)
    comment_keys = db.ListProperty(db.Key)
    prev_key = db.TextProperty()
    next_key = db.TextProperty()
    edit_time = db.ListProperty(datetime.datetime)
    pub_time = db.DateTimeProperty()
    pub_ip = db.TextProperty()
    
    def __unicode__(self):
        return self.title
    
    @property
    def abstract(self):
        return del_html(self.content)[:100]
        
    @property
    def profile(self):
        if self.author_profile:
            return self.author_profile
        else:
            email = str(self.author)
            try:
                name = email.split('@')[0]
            except:
                name = email
            userprofile = Profile.get_or_insert(u"key_%s"%email, author = self.author, displayname = name ,email = email)
            self.author_profile = userprofile
            self.put()
            return userprofile
        
    @property
    def comments(self):
        men_key = "%s_article_comment_%d"%(cur_app,self.key().id())
        men_data = memcache.get(men_key)
        if men_data is None:
            men_data = db.get(self.comment_keys[:10])
            memcache.add(men_key, men_data, 3600)
        return men_data
        
    @permalink
    def get_absolute_url(self):
        title = self.title.strip()
        title = title.replace(' ','_')
        title = title.replace(',','_')
        title = title.replace(u'，','_')
        title = title.replace("/","%2f")
        title = title.replace("%","%25")
        return ('app2.views.show_article', (), {'keyid': self.key().id(),'title':title})
    
    @permalink
    def short_url(self):
        return ('app2.views.show_article_short', (), {'keyid': self.key().id()})
    
    @property
    def next(self):
        if self.next_key:
            art = Entry.get(self.next_key)
            if art:
                return art
            else:
                self.next_key = None
                self.put()
                memcache.delete("%s_article_post_%d"%(cur_app,self.key().id()))
                return None
        else:
            art = Entry.all().order('pub_time').filter('pub_time >',self.pub_time).get()
            if art:
                self.next_key = str(art.key())
                self.put()
                memcache.delete("%s_article_post_%d"%(cur_app,self.key().id()))
                return art
            else:
                return None
    
    @property
    def prev(self):
        if self.prev_key:
            art = Entry.get(self.prev_key)
            if art:
                return art
            else:
                self.prev_key = None
                self.put()
                memcache.delete("%s_article_post_%d"%(cur_app,self.key().id()))
                return None
        else:
            art = Entry.all().order('-pub_time').filter('pub_time <',self.pub_time).get()
            if art:
                self.prev_key = str(art.key())
                self.put()
                memcache.delete("%s_article_post_%d"%(cur_app,self.key().id()))
                return art
            else:
                return None

signals.pre_delete.connect(cleanup_relations, sender=Entry)

class Comment(db.Model):
    author = db.ReferenceProperty(User, collection_name='user_bbs_comment')
    author_profile = db.ReferenceProperty(Profile)
    entry = db.ReferenceProperty(Entry, collection_name='post_comment')
    date = db.DateTimeProperty(auto_now_add=True)
    message = db.TextProperty(required=True)
    pub_ip = db.TextProperty()
    
    def __unicode__(self):
        return str(self.author)
    
    @property
    def profile(self):
        if self.author_profile:
            return self.author_profile
        else:
            email = str(self.author)
            try:
                name = email.split('@')[0]
            except:
                name = email
            userprofile = Profile.get_or_insert(u"key_%s"%email, author = self.author, displayname = name ,email = email)
            self.author_profile = userprofile
            self.put()
            return userprofile
    